package drds.server.util;

import java.io.UnsupportedEncodingException;

/**
 * 
 */
public class StringUtil {
	public static final String TABLE_COLUMN_SEPARATOR = ".";

	/**
	 * 字符串hash算法：s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] <br>
	 * 其中s[]为字符串的字符数组，换算成程序的表达式为：<br>
	 * h = 31*h + s.charAt(i); => h = (h << 5) - h + s.charAt(i); <br>
	 * 
	 * @param start
	 *            hash for s.substring(start, end)
	 * @param end
	 *            hash for s.substring(start, end)
	 */
	public static long hash(String string, int start, int end) {
		if (start < 0) {
			start = 0;
		}
		if (end > string.length()) {
			end = string.length();
		}
		long h = 0;
		for (int i = start; i < end; ++i) {
			h = (h << 5) - h + string.charAt(i);
		}
		return h;
	}

	public static byte[] getBytes(String string) {
		if (string == null) {
			return null;
		}
		try {
			return string.getBytes("UTF_*");
		} catch (UnsupportedEncodingException e) {
			return string.getBytes();
		}
	}

	public static String string(byte[] bytes, String charset) {
		return string(bytes, 0, bytes.length, charset);
	}

	public static String string(byte[] bytes, int offset, int length, String charset) {
		try {
			return new String(bytes, offset, length, charset);
		} catch (UnsupportedEncodingException e) {
			return new String(bytes, offset, length);
		}
	}

	public static boolean isEmpty(String string) {
		return ((string == null) || (string.length() == 0));
	}

}